package com.inossem.utils.permission;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.util.Log;

import com.inossem.utils.R;
import com.yanzhenjie.alertdialog.AlertDialog;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：wsy on 2017/11/2 15:12
 * <p>
 * 邮箱：445979770@qq.com
 */

public class PermissionUtils {

    private static final int REQUEST_CODE_PERMISSION = 100;

    public static final int REQUEST_CODE_SETTING = 300;

    private static OnApplyPermissionListener listener;

    private static PackageManager pManager ;

    private static Context mContext;

    // 在Fragment中这句话不能注释，否则Fragment接收不到获取权限的通知。
    //super.onRequestPermissionsResult(requestCode,permissions,grantResults);

    public static void applyForPermission (final Context context , final List<String> list , OnApplyPermissionListener onApplyPermissionListener) {
        String[] array=(String[])list.toArray(new String[list.size()]);
        listener = onApplyPermissionListener;
        mContext  = context;
        // 申请权限。
        AndPermission.with(mContext)
                .requestCode(REQUEST_CODE_PERMISSION)
//                .permission(Permission.CAMERA,Permission.LOCATION)
                .permission(array)
                .callback(permissionListener)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(rationaleListener)
                .start();
    }

    /**
     * 回调监听。
     */
    private static PermissionListener permissionListener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            switch (requestCode) {
                case REQUEST_CODE_PERMISSION: {
                    listener.onSuccessful();
                    break;
                }
            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {

            for (int i = 0; i < deniedPermissions.size(); i++) {
                Log.i("wang" , "deniedPermissions ==== " + deniedPermissions.get(i));
            }

            switch (requestCode) {
                case REQUEST_CODE_PERMISSION: {
                    // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
//                    if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
//                        // 第一种：用默认的提示语。
                        AndPermission.defaultSettingDialog((Activity) mContext, REQUEST_CODE_SETTING)
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                listener.onFailure();
                            }
                        }).show();
                    break;
                }
            }


            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
//            if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
//                 第一种：用默认的提示语。
//                AndPermission.defaultSettingDialog((Activity) mContext, REQUEST_CODE_SETTING).show();


                // 第二种：用自定义的提示语。
//             AndPermission.defaultSettingDialog((Activity) mContext, REQUEST_CODE_SETTING)
//                     .setTitle("权限申请失败")
//                     .setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权，否则功能无法正常使用！")
//                     .setPositiveButton("好，去设置").setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                 @Override
//                 public void onClick(DialogInterface dialogInterface, int i) {
////                     dialogInterface.cancel();
//                     Toast.makeText(mContext , "取消了！" , Toast.LENGTH_SHORT).show();
//                 }
//             })
//                     .show();

//            第三种：自定义dialog样式。
//            SettingService settingHandle = AndPermission.defineSettingDialog((Activity) mContext, REQUEST_CODE_SETTING);
//            你的dialog点击了确定调用：
//            settingHandle.execute();
//            你的dialog点击了取消调用：
//            settingHandle.cancel();
//            }
        }
    };

    /**
     *  判断所需要的权限是否都被允许，如果都被允许返回ture，否则返回false
     * @param context
     * @param list  所需权限的list
     * @return
     */
    public static boolean permissionIsAllow (Context context, List<String> list) {
        if (AndPermission.hasPermission(context ,list)) {
            return true;
        }else {
            return false;
        }
    }
    /**
     * Rationale支持，这里自定义对话框。
     */
    private static RationaleListener rationaleListener = new RationaleListener() {
        @Override
        public void showRequestPermissionRationale(int requestCode, final Rationale rationale) {
            // 这里使用自定义对话框，如果不想自定义，用AndPermission默认对话框：
            // AndPermission.rationaleDialog(Context, Rationale).show();

            // 自定义对话框。
            AlertDialog.newBuilder(mContext)
                    .setTitle(R.string.title_dialog)
                    .setMessage(R.string.message_permission_failed)
                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            rationale.resume();
                        }
                    })
                    .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            rationale.cancel();
                        }
                    }).show();
        }
    };

    public interface OnApplyPermissionListener {
        void onSuccessful();

        void onFailure();
    }

    public static List<String> getManifestPermission (Context context , String packageName) {
        pManager = context.getPackageManager();
        List<String> list = new ArrayList<>();
        try {
            PackageInfo pack = pManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
            String[] permissionStrings = pack.requestedPermissions;
            for (int i = 0; i < permissionStrings.length; i++) {
                for (int j = 0; j < dangerPermission().size(); j++) {
                    if (permissionStrings[i].equals(dangerPermission().get(j))) {
                        list.add(permissionStrings[i]);
                    }
                }
            }
            return list;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static List<String> dangerPermission () {
        List<String> dangerPermissionList = new ArrayList<>();
        dangerPermissionList.add("android.permission.WRITE_CONTACTS");
        dangerPermissionList.add("android.permission.GET_ACCOUNTS");
        dangerPermissionList.add("android.permission.READ_CONTACTS");
        dangerPermissionList.add("android.permission.READ_CALL_LOG");
        dangerPermissionList.add("android.permission.READ_PHONE_STATE");
        dangerPermissionList.add("android.permission.CALL_PHONE");
        dangerPermissionList.add("android.permission.WRITE_CALL_LOG");
        dangerPermissionList.add("android.permission.USE_SIP");
        dangerPermissionList.add("android.permission.PROCESS_OUTGOING_CALLS");
        dangerPermissionList.add("com.android.voicemail.permission.ADD_VOICEMAIL");
        dangerPermissionList.add("android.permission.READ_CALENDAR");
        dangerPermissionList.add("android.permission.WRITE_CALENDAR");
        dangerPermissionList.add("android.permission.CAMERA");
        dangerPermissionList.add("android.permission.BODY_SENSORS");
        dangerPermissionList.add("android.permission.ACCESS_FINE_LOCATION");
        dangerPermissionList.add("android.permission.ACCESS_COARSE_LOCATION");
        dangerPermissionList.add("android.permission.READ_EXTERNAL_STORAGE");
        dangerPermissionList.add("android.permission.WRITE_EXTERNAL_STORAGE");
        dangerPermissionList.add("android.permission.RECORD_AUDIO");
        dangerPermissionList.add("android.permission.READ_SMS");
        dangerPermissionList.add("android.permission.RECEIVE_WAP_PUSH");
        dangerPermissionList.add("android.permission.RECEIVE_MMS");
        dangerPermissionList.add("android.permission.RECEIVE_MMS");
        dangerPermissionList.add("android.permission.SEND_SMS");
        dangerPermissionList.add("android.permission.READ_CELL_BROADCASTS");

        return dangerPermissionList;
    }

    /**
     * 获取当前应用程序的包名
     * @param context 上下文对象
     * @return 返回包名
     */
    public static String getAppProcessName(Context context) {
        //当前应用pid
        int pid = android.os.Process.myPid();
        //任务管理类
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        //遍历所有应用
        List<ActivityManager.RunningAppProcessInfo> infos = manager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo info : infos) {
            if (info.pid == pid)//得到当前应用
                return info.processName;//返回包名
        }
        return "";
    }
}
